/*
 * @Copyright: Citylife 2021
 * @Author: shaokui.gu
 * @Date: 2021-01-18 14:56:18
 * @Description: 
 */

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'colors_dark.dart';
import 'colors_light.dart';
import 'theme_colors.dart';

class ThemeManager with WidgetsBindingObserver {
  /// 单利
  static ThemeManager _instance;

  /// get
  static ThemeManager get instance {
    if (_instance == null) {
      _instance = ThemeManager().._initilized();
    }
    return _instance;
  }

  void _initilized() {
    WidgetsBinding.instance.addObserver(this);
  }

  /// 主题控制模式
  final _themeMode = ThemeMode.light.obs;
  ThemeMode get themeMode => this._themeMode.value;
  set themeMode(ThemeMode value) {
    if (value == ThemeMode.system) {
      final Brightness brightnessValue =
          WidgetsBinding.instance.window.platformBrightness;
      _isDark = brightnessValue == Brightness.dark;
      _colors = isDark ? _darkColors : _lightColors;
    } else {
      _isDark = (value == ThemeMode.dark);
      _colors = _isDark ? _darkColors : _lightColors;
    }
    _updateThemeMode(value);
    this._themeMode.value = value;
    Get.forceAppUpdate();
  }

  final ThemeColors _lightColors = ThemeLightColors();
  final ThemeColors _darkColors = ThemeDarkColors();

  ThemeColors _colors = ThemeLightColors();
  bool _isDark;
  bool get isDark {
    return _isDark;
  }

  ThemeColors get colors {
    return _colors;
  }

  Future<void> init() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    int index = prefs.getInt("theme_mode") ?? 1;
    themeMode = ThemeMode.values[index];
  }

  _updateThemeMode(ThemeMode mode) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setInt("theme_mode", ThemeMode.values.indexOf(mode));
  }

  @override
  void didChangePlatformBrightness() {
    super.didChangePlatformBrightness(); // make sure you call this
    if (theme.themeMode == ThemeMode.system) {
      themeMode = ThemeMode.system;
    }
  }
}

/// 全局theme对象
ThemeManager theme = ThemeManager.instance;
